package com.alibaba.service.impl;

import com.alibaba.mapper.ActivityProductMapper;
import com.alibaba.model.entity.ActivityProduct;
import com.alibaba.model.entity.Product;
import com.alibaba.service.ActivityProductService;
import com.alibaba.utils.BizException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 活动商品服务实现类，实现ActivityProductService接口。
 */
@Service
public class ActivityProductServiceImpl implements ActivityProductService {

    @Resource
    private ActivityProductMapper activityProductMapper;

    @Override
    public List<ActivityProduct> listProductsByActivityId(Long activityId) {
        return activityProductMapper.selectByActivityId(activityId);
    }

    @Override
    public List<ActivityProduct> listActivitiesByProductId(Long productId) {
        return activityProductMapper.selectByProductId(productId);
    }

    @Override
    public boolean addActivityProduct(ActivityProduct activityProduct) {
        int rows = activityProductMapper.insert(activityProduct);
        if (rows <= 0) {
            throw new BizException("新增活动商品关联失败，activityProduct：" + activityProduct.toString());
        }
        return true;
    }

    @Override
    public boolean updateActivityProductStock(Long activityId, Long productId, Integer stock) {
        ActivityProduct ap = new ActivityProduct(activityId, productId, stock);
        int rows = activityProductMapper.updateById(ap);
        if (rows <= 0) {
            throw new BizException("更新活动商品库存失败，activityId：" + activityId + ", productId：" + productId);
        }
        return true;
    }

    @Override
    public boolean deleteActivityProduct(Long activityId, Long productId) {
        // 这里假设有联合主键，需自定义删除方法，或用条件删除
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ActivityProduct> wrapper =
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        wrapper.eq("activity_id", activityId).eq("product_id", productId);
        int rows = activityProductMapper.delete(wrapper);
        if (rows <= 0) {
            throw new BizException("删除活动商品关联失败，activityId：" + activityId + ", productId：" + productId);
        }
        return true;
    }

    @Override
    public List<Product> selectOngoingProduct() {
        // 获取当前时间（系统默认时区）
        LocalDateTime now = LocalDateTime.now();
        // 将当前时间传给 Mapper
        return activityProductMapper.selectOngoingProduct(now);
    }

}
